﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Reflection;
using System.Web;
using Songhay.Data;

namespace Songhay.Web
{

    public partial class DataActivtyServer : HttpApplication
    {
        static void Start(RequestBag ReqBag)
        {
            DataActivtyServer._log.AppendLine("Starting Data Activity Server (Start())...");

            //Load conventional DataAccessConfiguration.xml file:
            DataActivtyServer._dbmsMetaXml = ReqBag.Context.Server.MapPath("./App_Data/DataAccessConfiguration.xml");
            DataActivtyServer._log.AppendLine(String.Format("Data Activity Configuration: {0}", DataActivtyServer._dbmsMetaXml));
            if(!File.Exists(DataActivtyServer._dbmsMetaXml)) throw new ConfigurationErrorsException(String.Format("XML file [{0}] not found.", DataActivtyServer._dbmsMetaXml));
            DataActivtyServer._log.AppendLine(String.Format("Data Activity Client Data: {0}", DataActivtyServer._clientXsl));

            //Load conventional Client.xslt file:
            DataActivtyServer._clientXsl = ReqBag.Context.Server.MapPath("./xslt/Client.xslt");
            if(!File.Exists(DataActivtyServer._clientXsl)) throw new ConfigurationErrorsException(String.Format("XSL file [{0}] not found.", DataActivtyServer._clientXsl));

            //When data connection ID found, set static data for Server Application:
            DataActivtyServer._log.AppendLine("Loading Data Activity Configuration(s)...");
            DataActivtyServer._dataManagers = new Dictionary<string, ICommandHandler>();
            DataActivtyServer._dbmsMeta = new DataAccessConfiguration(DataActivtyServer._dbmsMetaXml);

            foreach(DataAccessItem dBInfo in DataActivtyServer._dbmsMeta.DataAccessItem)
            {
                DataActivtyServer._log.AppendLine(String.Format("Loading Assembly: {0}", dBInfo.Path));
                Assembly dll = Assembly.LoadFile(dBInfo.Path);
                ICommandHandler commandHandler = dll.CreateInstance(dBInfo.TypeName) as ICommandHandler;
                commandHandler.ReadDataAccessItem(dBInfo);
                DataActivtyServer._dataManagers.Add(dBInfo.Name, commandHandler);
            }
        }
    }
}